// https://qna.habr.com/q/588117?ysclid=lwae934lht617858848
import { RefObject, useEffect, useState } from 'react';

import { Router } from 'next/router';

export const useScrollLock = (ref?: RefObject<any>) => {
  const [body, setBody] = useState<HTMLElement>();

  useEffect(() => {
    if (ref) {
      setBody(ref.current);
    }
    if (typeof window === 'undefined') return;
    setBody(document.body);
  }, [ref]);
  const lock = () => {
    if (body) {
      setTimeout(() => {
        if (!document.body.hasAttribute('data-body-scroll-fix')) {
          const scrollPosition = window.scrollY || document.documentElement.scrollTop;

          document.body.setAttribute('data-body-scroll-fix', String(scrollPosition));
          document.body.style.overflow = 'hidden';
          document.body.style.position = 'fixed';
          document.body.style.top = `-${scrollPosition}px`;
          document.body.style.left = '0';
          document.body.style.width = '100%';
        }
      }, 25);
    }
  };

  const unlock = () => {
    if (body) {
      if (document.body.hasAttribute('data-body-scroll-fix')) {
        const scrollPosition = document.body.getAttribute('data-body-scroll-fix');

        document.body.removeAttribute('data-body-scroll-fix');

        document.body.style.overflow = '';
        document.body.style.position = '';
        document.body.style.top = '';
        document.body.style.left = '';
        document.body.style.width = '';

        window.scroll(0, Number(scrollPosition));
      }
    }
  };

  useEffect(() => {
    Router.events.on('routeChangeComplete', unlock);
    return () => {
      Router.events.off('routeChangeComplete', unlock);
    };
  }, []);

  return {
    lock,
    unlock,
  };
};
